#include <iostream>
#include <memory>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "LogMessage.hpp"
#include "ExistReason.hpp"
#include "Pthread.hpp"

void Usage()
{
    Log::LogMessage(Error, "Please enter:  ./Client [ip] port");
}

struct ThreadDate
{
    ThreadDate(int sock, sockaddr_in addr)
        : _sock(sock), _addr(addr)
    {
    }

    int _sock;
    sockaddr_in _addr;
};

void Sender(ThreadDate date)
{
    while (true)
    {
        std::string buffer;
        std::cout << "Please enter# ";
        std::getline(std::cin, buffer);
        sendto(date._sock, buffer.c_str(), buffer.size(), 0, (sockaddr *)&date._addr, sizeof(date._addr));
        if (sendto <= 0)
        {
            std::cerr << "send error" << std::endl;
        }
    }
}

void Recver(ThreadDate date)
{
    char mes[1024];
    while (true)
    {
        sockaddr_in add;
        socklen_t addlen = sizeof(add);
        int n = recvfrom(date._sock, mes, sizeof(mes) - 1, 0, (sockaddr *)&add, &addlen);
        if (n > 0)
        {
            mes[n] = '\0';
            std::cerr << mes << std::endl;
        }
    }
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage();
        return USE_ERROR_MANUAL;
    }

    std::string ip = argv[1];
    uint16_t port = atoi(argv[argc - 1]);
    // 创建套接字
    int clientsocket = socket(AF_INET, SOCK_DGRAM, 0);
    if (clientsocket < 0)
    {
        Log::LogMessage(Error, "create socket error");
        exit(CREATE_SOCKET_ERROR);
    }
    Log::LogMessage(Debug, "create socket success, socket: %d", clientsocket);

    // 直接给服务器send，系统会自动帮我们bind
    sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = inet_addr(ip.c_str());

    ThreadDate date(clientsocket, addr);
    Thread<void, ThreadDate> sender(Sender, date);
    Thread<void, ThreadDate> recver(Recver, date);
    sender.Create();
    recver.Create();

    sender.Jion();
    recver.Jion();

    return 0;
}